package com.zszedu.service;

import com.zszedu.mapper.AccountMapper;
import com.zszedu.mapper.BigInfoMapper;
import com.zszedu.mapper.ProductMapper;
import com.zszedu.pojo.Account;
import com.zszedu.pojo.BidInfo;
import com.zszedu.pojo.Product;
import com.zszedu.vo.BigInfoVo;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;


@DubboService
public class BigInfoServiceImpl implements BigInfoService {
    @Autowired
    private BigInfoMapper bigInfoMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private AccountMapper accountMapper;

    //查询 Money 总和
    @Override
    public Double queryMoney() {
        return bigInfoMapper.queryMoney();
    }

    @Override
    public List<Map> queryTopMoney(Integer limit) {
        return bigInfoMapper.queryTopMoney(limit);
    }

    @Override
    public List<BigInfoVo> query(Long id) {
        return bigInfoMapper.query(id, 5);
    }

    @Override
    public List<BidInfo> queryRecentInvest(Long uid) {
        return bigInfoMapper.queryRecentInvest(uid);
    }

    /**
     * @param uid 用户id
     * @param pid 产品id
     * @param money 投资金额(u_finance_account表中的available_money字段)
     */
    @Transactional //添加事务，防止购买后金额扣款失败
    public void Invest(Long uid, Integer pid, Double money) {
        //判断投资金额是否满足条件(大于最低投资金额100/小于最高投资金额，只能整百整百的投资)
        if (money < 0 || money % 100 != 0){
            throw new RuntimeException("投资金额必须，整百整百的投资！");
        }
        
        //查询投资的产品信息
        Product product = productMapper.queryById(pid);
        if (money < product.getBidMinLimit() || money > product.getBidMaxLimit()){
            throw new RuntimeException("投资金额必须在" + product.getBidMinLimit() +"~"+ product.getBidMaxLimit() + "之间！");
        }

        //判断用户金额是否充足扣除用户金额(在数据库中判断，如果需要扣款的金额大于数据库中的金额，则返回0)
        Integer integer = accountMapper.editMoney(uid, money);
        if (integer == 0){
            throw new RuntimeException("余额不足，请先充值！");
        }

        //扣除产品剩余购买金额
        Integer editMoney = productMapper.editMoney(pid, money);
        if (editMoney == 0){
            throw new RuntimeException("产品余额不足，请更换产品购买！");
        }

        //判断产品剩余金额是否为0(为0则更新，产品状态为满标/产品满标时间)
        //使用上面获取到的产品信息，(产品剩余金额 - 投资金额 < 产品最小投资金额) 为T则产品已满标
        if (product.getLeftProductMoney() - money < product.getBidMinLimit()){
            productMapper.editStatusAndTime(pid,1,new Date());
        }

        //添加投资记录
        BidInfo bidInfo = new BidInfo();
        bidInfo.setProdId(pid);
        bidInfo.setUid(uid);
        bidInfo.setBidMoney(money);
        bidInfo.setBidTime(new Date());
        bidInfo.setBidStatus(1);
        bigInfoMapper.addBidInfo(bidInfo);
    }

    @Override
    public List<BidInfo> queryByPid(Long pid) {
        return bigInfoMapper.queryByPid(pid);
    }
}
